package io.github.config;

import io.github.annotation.Log;
import io.github.entity.SysLogEntity;
import io.github.entity.SysUserEntity;
import io.github.service.SysLogService;
import io.github.util.IpUtil;
import io.github.util.ShiroUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Author: Max
 * @Date: 2019/10/8 15:26
 */

@Aspect
@Component
public class LogAspect {

    @Autowired
    private SysLogService logService;

    @Autowired
    private HttpServletRequest request;

    @Pointcut("@annotation(io.github.annotation.Log)")
    public void pointcut(){

    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;
        try {
            insertLog(point);
            result = point.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return result;
    }

    private void insertLog(ProceedingJoinPoint point){
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        SysLogEntity entity = new SysLogEntity();

        Log userAction = method.getAnnotation(Log.class);

        if(userAction != null){
            entity.setUserAction(userAction.value());
            entity.setAction(userAction.action());
        }

        SysUserEntity userEntity = ShiroUtils.getAdminEntity();

        if(userEntity!=null){
            entity.setUserName(userEntity.getUsername());
            entity.setUserNick(userEntity.getNickname());
            entity.setCreateTime(new Date());
            entity.setIp(IpUtil.getIpAddr(request));

            logService.save(entity);
        }

    }

}
